<?php
class config
{
    private $config_array = null;
    private $config_name = '';

    private function &__construct($config_name)
    {
        $config_file = CONFIG.$config_name.'.ini';

        if (!file_exists($config_file))
        {
            copy(CONFIG.'config_template.ini', $config_file);
        }

        $config = $this->parse_file($config_file);

        $this->config_array = $config;
    }

    private function parse_key(&$section, $key, $value)
    {
        if (strpos($key,'.') !== false)
        {
            $pieces = explode('.',$key,2);
            $section[$pieces[0]] = $this->parse_key($section[$pieces[0]],$pieces[1],$value);
            unset($section[$key]);
        }
        else
        {
            $section[$key] = $value;
        }
        return $section;

    }

    private function parse_file($filename)
    {
        $config = parse_ini_file($filename,true);

        foreach($config as &$section)
        {
            foreach($section as $key=>$value)
            {
               $this->parse_key($section,$key,$value); 
            }
        }

        return $config;
    }

    public function get($path = null)
    {
        $parts = explode('/',$path);
        $value = $this->config_array;
        foreach ($parts as $part)
        {
            if ($part != '')
                $value = $value[$part];
        }
        return $value;
    }
    
    static public function file($config_name = '')
    {
        static $instances = array();

        if (empty($config_name))
            $config_name = $_SERVER['HTTP_HOST'];

        return $instances[$config_name] = new config($config_name);
    }
}
?>
